package com.vhall.component.service.interactive.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vhall.component.dao.interactive.DocumentsRoomMapper;
import com.vhall.component.entity.account.vo.AccountVO;
import com.vhall.component.entity.interactive.vo.*;
import com.vhall.component.entity.room.RoomDocumentsEntity;
import com.vhall.component.entity.room.enums.DocumentTransNameEnum;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.constant.ConstStr;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.support.TokenThreadLocal;
import com.vhall.component.service.account.AccountService;
import com.vhall.component.service.interactive.DocumentsAdminService;
import com.vhall.component.service.interactive.DocumentsRoomService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author song.dong
 * @date 2021-07-29 18:45
 */
@Slf4j
@Service
public class DocumentsAdminServiceImpl implements DocumentsAdminService {

    @Autowired
    private DocumentsRoomMapper documentsRoomMapper;

    @Autowired
    private DocumentsRoomService documentsRoomService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public DocumentAdminListRspVO list(DocumentAdminListReqVO vo) {
        Page<RoomDocumentsEntity> page = new Page<>(vo.getPage(), vo.getPagesize());
        LambdaQueryWrapper<RoomDocumentsEntity> query = Wrappers.lambdaQuery();
        query.like(StringUtils.isNotEmpty(vo.getKeyword()), RoomDocumentsEntity::getFileName, vo.getKeyword());
        query.ge(StringUtils.isNotEmpty(vo.getBeginTime()), RoomDocumentsEntity::getCreatedAt, vo.getBeginTime() + " " + ConstStr.TIME_ZERO);
        query.le(StringUtils.isNotEmpty(vo.getEndTime()), RoomDocumentsEntity::getCreatedAt, vo.getEndTime() + " " + ConstStr.TIME_FULL);
        query.eq(StringUtils.isNotEmpty(vo.getTransformSchedule()), RoomDocumentsEntity::getTransStatus, vo.getTransformSchedule());
        query.eq(StringUtils.isNotEmpty(vo.getAppId()), RoomDocumentsEntity::getAppId, vo.getAppId());
        query.eq(StringUtils.isNotEmpty(vo.getDocumentId()), RoomDocumentsEntity::getDocumentId, vo.getDocumentId());
        query.orderByDesc(RoomDocumentsEntity::getCreatedAt);
        page = documentsRoomMapper.selectPage(page, query);
        int total = 0;
        List<DocumentAdminListSingle> data = new ArrayList<>();
        if (page != null) {
            total = Integer.parseInt(String.valueOf(page.getTotal()));
            List<RoomDocumentsEntity> records = page.getRecords();
            if (CollectionUtils.isNotEmpty(records)) {
                // 查询account表获取数据。
                // 查询account表获取username.
                String ids = records.parallelStream().map(RoomDocumentsEntity::getAccountId).collect(Collectors.joining(","));
                List<AccountVO> accounts = accountService.listByIds(ids);
                Map<Integer, String> map = accounts.stream().collect(Collectors.toMap(AccountVO::getAccountId, AccountVO::getUsername));
                DocumentAdminListSingle singleNew;
                Map<String, String> singleAccount;
                for (RoomDocumentsEntity single : records) {
                    singleNew = new DocumentAdminListSingle();
                    singleAccount = new HashMap<>(4);
                    singleAccount.put("nick_name", map.get(Integer.valueOf(single.getAccountId())));
                    BeanUtils.copyProperties(single, singleNew);
                    singleNew.setTransName(DocumentTransNameEnum.getDescription(single.getTransStatus()));
                    singleNew.setAccount(singleAccount);
                    data.add(singleNew);
                }
            }
        }
        DocumentAdminListRspVO resp = new DocumentAdminListRspVO();
        resp.setCurrentPage(vo.getPage());
        resp.setPerPage(vo.getPagesize());
        resp.setTotal(total);
        resp.setData(data);
        return resp;
    }

    @Override
    public DocumentDeleteRespVO delete(DocumentConsoleDeleteReqVO reqVO) {
        Token token = TokenThreadLocal.getToken();
        if (null == token) {
            throw new BusinessException(BizErrorCode.AUTH_LOGIN_NEEDS);
        }
        DocumentDeleteRespVO documentDeleteRespVO = new DocumentDeleteRespVO();
        int delCount = 0;
        List<String> documentList = new ArrayList<>();
        List<String> documentIds = Arrays.stream(reqVO.getDocumentIds().split(",")).collect(Collectors.toList());
        for (String documentId : documentIds) {
            if (StringUtils.isNotBlank(documentId) && redisTemplate.opsForZSet().score(RedisKey.ROOM_DOC, documentId) == null) {
                //判断当前文档是否正在演示中，非演示中可以删除
                DocumentDeleteReqVO vo = new DocumentDeleteReqVO();
                vo.setDocumentId(documentId.trim());
                documentsRoomService.delete(vo);
                delCount++;
            } else {
                documentList.add(documentId.trim());
            }
        }
        documentDeleteRespVO.setNotDelIds(documentList);
        documentDeleteRespVO.setDelCount(delCount);
        return documentDeleteRespVO;
    }
}
